<template>
<!-- 预算调整单 -->
<section class="content-box">
	<div v-if="isshowList">
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-form class="title">
				<h2>预算调整单</h2>
				<el-form-item>
					<el-button type="success" @click="handleAdd">新建</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table v-if="budgetAdjustList" :data="budgetAdjustList" highlight-current-row max-height="700" v-loading="loading" element-loading-text="正在加载中">
			<el-table-column prop="BA_DocNO" label="单号">
			</el-table-column>
			<el-table-column prop="Dept_Name" label="部门">
			</el-table-column>
			<el-table-column prop="UserName" label="编制人">
			</el-table-column>
			<el-table-column prop="BA_Abstract" label="标题">
			</el-table-column>
			<el-table-column prop="DocStatus" label="状态" sortable>
			</el-table-column>
			<el-table-column label="操作" min-width="200">
				<template slot-scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">&#12288;编辑&#12288;</el-button>
					<el-button v-if="scope.row.DocStatus==='待审核'" type="info" size="small" @click="repeal(scope.$index, scope.row)">&#12288;撤销&#12288;</el-button>
					<el-button type="warning" size="small" @click="checkflowRow(scope.$index, scope.row)">查看流程</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">&#12288;删除&#12288;</el-button>
        </template>
			</el-table-column>
		</el-table>
		<!--流程图-->
		<el-dialog title="流程执行情况" :visible.sync="checkflowRowVisible" :modal-append-to-body="false" align="center">
			<el-table :data="docRowView" header-align="center" v-loading="docViewloading" element-loading-text="拼命刷新中...">
				<el-table-column property="PlanUser" label="操作人"></el-table-column>
				<el-table-column property="StepName" label="步骤名称"></el-table-column>
				<el-table-column property="OpDate" label="时间"></el-table-column>
				<el-table-column property="OpRemark" label="备注"></el-table-column>
			</el-table>
		</el-dialog>
	</div>
	<!--新建页面-->
	<div v-if="isshowAdd">
		<!-- 导航条 -->
			<div class="flex-top">
				<div>
					<i class="el-icon-arrow-left back" @click="addToBack"></i>
					<span style="font-size:20px;vertical-align:middle;margin:0 10px;">
						预算调整单 </span>
					<small>
						<span>状态：</span>
						<el-tag type="success">新增</el-tag>
					</small>
				</div>
				<!-- 右侧 -->
				<div class="flex">
					<span class="wrapper">
						<el-button type="info" @click="addSave">
							<i class="icon iconfont icon-baocun"></i> 保存
						</el-button>
						<el-button type="success" @click="addSubmit">
							<i class="el-icon-circle-check"></i> 提交
						</el-button>
					</span>
				</div>
			</div>
			<!-- 中部 -->
			<main class="main">
				<div class="main-left">
				  <div>
					<h3>日期：</h3>
					<div class="flex">
						<el-date-picker type="date" placeholder="选择日期" v-model="docDate">
						</el-date-picker>
					</div>
					</div>
				</div>
				<div class="main-right">
					<div class="left-form">
						<el-row>
							<el-col :span="24">
								<span>预算类型：</span>
								<el-select v-model="BudgetType" style="margin-left:20px;" @change="Clear()">
									<el-option v-for="(items,index) in BudgetTypeList" :key="index" :value="items.Code" :label="items.Name">
									</el-option>
								</el-select>
							</el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
								<span>调整方式：</span>
								<el-select v-model="AdjustModel" style="margin-left:20px;">
									<el-option v-for="(items,index) in AdjustModelList" :key="index" :value="items.Code" :label="items.Name">
									</el-option>
								</el-select>
							</el-col>
						</el-row>
					</div>
          <div class="right-form">
						<span>业务描述</span><br><br>
            <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
            v-model="describe" 
            class="textarea-title">
            </el-input>
					</div>
				</div>
			</main>
			<!--底部 预算明细 -->
		  <div class="budget">
        <div style="padding:10px;">     
          <span><i class="icon iconfont icon-iconfontcolor52"></i> 预算明细</span>&#x3000;
          <el-button class="add-button" type="primary" size="mini" @click="addlist">添加行</el-button>
        </div>
        <table class="HideTable" border="1">
          <tr>
            <th>金额</th>
            <th>月份</th>
            <th>费用承担部门</th>
            <th>费用类型</th>
            <th>预算余额</th>
            <th>操作</th>
          </tr>
          <tr v-for="(i,index) in detail" :key="index">
            <!-- 遍历初始化的detail添加行空数据 -->
            <td>
              <el-input type="number" v-model.number="i.BorrowLine_BorrowMoney" class="formval-money"></el-input>
              <!-- v-model => 金额 -->
            </td>
            <td>
              <el-select class="formVal" v-model="i.Month" @change="changeMonth(index,i.Month)">
                <el-option v-for="(item,index) in Month" :value="item.Code" :key="index" :label="item.Name">
                </el-option>
              </el-select>
            </td>
            <td>
              <el-select class="formVal" v-model="i.YBL_Department" @change="changeSelect(index,i.YBL_Department)">
                <!-- v-model => 费用承担部门 -->
                <el-option v-for="(item,index) in bears" :value="item.CODE" :key="index" :label="item.FULLNAME">
                  <!-- 部门名称 -->
                </el-option>
              </el-select>
            </td>
            <td>
              <!-- BorrowLine_YBL 费用类型iD??? -->
              <el-select class="formVal" @change="ChangeMoney(index)" v-model="i.BorrowLine_YBL">   
                <!-- v-model => 费用类型 -->
                <el-option v-for="(item,index) in i.costTypes" :value="item.ID" :key="item.ID" :label="item.BudgetItem_Name">
                </el-option>
              </el-select>
            </td>
            <td>
              <span class="budgetBalance">{{i.balance}}</span>
              <!-- 预算金额 -->
            </td>
            <td>
              <el-button size="small" @click="handleDelete(index)" type="danger" class="dele">删除</el-button>
            </td>
          </tr>
        </table>
      </div>
	</div>
  <!-- 
		编辑/待审核/已审核/已发起/未发起 界面 		
	-->
	<div v-if="isshowEdit">
    <!-- 导航条 -->
		<div class="flex-top">
			<div>
				<i class="el-icon-arrow-left back" @click="editToBack"></i>
				<span style="font-size:20px;vertical-align:middle;margin:0 10px;">
					预算调整单</span>
				<small>
					<span>状态：</span>
					<el-tag type="success">{{Type===1?'修改':Type===2?'查看':Type===3?'待审核':''}}</el-tag>
				</small>
			</div>
      <!-- 右侧 -->
			<div class="flex">
				<span class="wrapper">
					<el-button type="success" @click="auditBudget" :disabled="Type===1||Type===2">
						<i class="el-icon-circle-check"></i> 审核
					</el-button>
          <el-button v-if="Type===3" type="warning" @click="rejectBudget">
						<i class="el-icon-circle-close"></i> 驳回
					</el-button>
					<el-button type="info">
						<i class="icon iconfont icon-attachment"></i> 附件
					</el-button>
					<el-button type="warning"  @click="checkflow">
						<i class="icon iconfont icon-liucheng"></i> 查看流程
					</el-button>
					<el-button type="info" @click="editSave" :disabled="Type===2||Type===3">
						<i class="icon iconfont icon-baocun"></i>保存
					</el-button>
					<el-button type="success" @click="editSubmit" :disabled="Type===2||Type===3">
						<i class="el-icon-circle-check"></i>提交
					</el-button>
				</span>
			</div>
    </div>
      <!--流程图-->
			<el-dialog title="流程执行情况" :visible.sync="checkflowVisible" :modal-append-to-body="false" align="center">
				<el-table :data="docView" header-align="center" v-loading="docViewloading" element-loading-text="拼命刷新中...">
					<el-table-column property="PlanUser" label="操作人"></el-table-column>
					<el-table-column property="StepName" label="步骤名称"></el-table-column>
					<el-table-column property="OpDate" label="时间"></el-table-column>
					<el-table-column property="OpRemark" label="备注"></el-table-column>
				</el-table>
      </el-dialog>
      <!-- 中部 -->
			<main class="main">
				<div class="main-left">
          <div>
            <h3>单号:</h3>
            <strong>{{DocNo}}</strong>
          </div>
				  <div>
					<h3>日期：</h3>
					<div class="flex">
						<el-date-picker type="date" placeholder="选择日期" v-model="docDate">
						</el-date-picker>
					</div>
					</div>
				</div>
				<div class="main-right">
					<div class="left-form">
						<el-row>
							<el-col :span="24">
								<span>预算类型：</span>
								<el-select v-model="BudgetType" style="margin-left:20px;" @change="Clear()">
									<el-option v-for="(items,index) in BudgetTypeList" :key="index" :value="items.Code" :label="items.Name">
									</el-option>
								</el-select>
							</el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
								<span>调整方式：</span>
								<el-select v-model="AdjustModel" style="margin-left:20px;">
									<el-option v-for="(items,index) in AdjustModelList" :key="index" :value="items.Code" :label="items.Name">
									</el-option>
								</el-select>
							</el-col>
						</el-row>
					</div>
          <div class="right-form">
						<span>业务描述</span><br><br>
            <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
            v-model="describe" 
            class="textarea-title">
            </el-input>
					</div>
				</div>
			</main>
      <!--底部 预算明细 -->
		  <div class="budget">
        <div style="padding:10px;">     
          <span><i class="icon iconfont icon-iconfontcolor52"></i> 预算明细</span>&#x3000;
          <el-button class="add-button" type="primary" size="mini" @click="addlist">添加行</el-button>
        </div>
        <table class="HideTable" border="1">
          <tr>
            <th>金额</th>
            <th>月份</th>
            <th>费用承担部门</th>
            <th>费用类型</th>
            <th>预算余额</th>
            <th>操作</th>
          </tr>
          <tr v-for="(i,index) in detail" :key="index">
            <!-- 遍历初始化的detail添加行空数据 -->
            <td>
              <!-- 这里绑定的是 BorrowLine_BorrowMoney -->
              {{ i.ID }}
              <el-input type="number" v-model.number="i.BorrowLine_BorrowMoney" class="formval-money" :disabled="Type===2||Type===3"></el-input>
              <!-- v-model => 金额 -->
            </td>
            <td>
              <el-select class="formVal" v-model="i.Month">
                <el-option v-for="(item,index) in Month" :value="item.Code" :key="index" :label="item.Name" >
                </el-option>
              </el-select>
            </td>
            <td>
              {{i.YBL_Department}}
              <el-select class="formVal" v-model="i.YBL_Department" @change="changeSelect(index,i.YBL_Department)">
                <!-- v-model => 费用承担部门 -->
                <el-option v-for="(item,index) in bears" :value="item.CODE" :key="index" :label="item.FULLNAME">
                  <!-- 部门名称 -->
                </el-option>
              </el-select>
            </td>
            <td>
              {{i.BorrowLine_YBL+ 'ID'}}
              <!-- BorrowLine_YBL 费用类型iD -->
              <el-select class="formVal"  v-model="i.BorrowLine_YBL" @change="ChangeMoney(index)"> 
                <!-- v-model => 费用类型 -->
                <el-option v-for="(item,index) in i.costTypes" :value="item.ID" :key="index" :label="item.BudgetItem_Name">
                </el-option>
              </el-select>
            </td>
            <td>
              <span class="budgetBalance">{{i.balance}}</span>
              <!-- 预算金额 -->
            </td>
            <td>
              <el-button size="small" @click="handleDelete(index)" type="danger" class="dele">删除</el-button>
            </td>
          </tr>
        </table>
      </div>
    </div>
</section>
</template>

<script>
import axios from "../../util/axios";
export default {
  name: "budegetAdjust",
  data() {
    return {
      showNum:"",//传过来的参数
      key:"",
      Msg: "", //审核提醒
      isshowList: true,
      isshowAdd: false,
      isshowEdit: false,
      checkflowRowVisible: false, //外面的流程图
      checkflowVisible: false, //里面的流程图
      bears: [], //获取费用承担部门数据
      budgetAdjustList: [], //列表
      docRowView: [], //外部流程图列表
      docView: [], //内部流程图列表
      loading: true,
      docViewloading: false,
      docDate: "", //初始化日期
      DocNo:"",//单号
      arrangeMode: "", //调整方式
      describe: "", //业务描述
      budgetDetail:[],//详情
      AdjustModelList: [], //调整方式
      AdjustModel: "",
      BudgetTypeList: [], //预算类型
      BudgetType: "",
      Type: 0, //0添加  1修改 2查看  3待
      detail: [
        {
          BorrowLine_BorrowMoney: 0, //金额
          YBL_Department: "", //费用承担部门
          BorrowLine_YBL: "", //费用类型
          balance: "", //预算金额
          Month: 0,
          costTypes: []
        }
      ],
      detailTemp: [], //获取借款单明细
      Month: [],
      MonthParams: 0,
      //沟通模块
      dialogCommunicationVisible:false,//沟通窗口      
      CommunicationContentList:[],//沟通内容列表
      contentInput:'',//输入内容Model
      acquiescenceImg:'static/content/images/Header-S.png',//默认头像
      LaunchList:[],//沟通对象集合
      launch:[],//沟通对象
      launchChecked:false,//是否允许编辑
      requestEmp:'',//申请人ID
      communiTypes:0,//获取沟通状态
      isshowLauch:false,
      DocType: 203,//单据类型 报销单=301 借款单=302  还款单=303 收入确认单=304  出纳付款=401  出纳收款=402
    };
  },
  methods: {
    getList() {
      axios
        .get("getBudgetAdjustList", {
          page: 1, //一页
          rows: 5000 //显示5000条
        })
        .then(res => {
          this.loading = true;
          this.budgetAdjustList = res.rows;
          setTimeout(() => {
            this.loading = false;
          }, 500);
        });
    },
    // 新建返回到列表页面
    addToBack() {
      this.isshowAdd = false; //新建页面隐藏
      this.isshowList = true; //列表页面显示
      this.getList();
    },
    // 编辑返回列表页面
    editToBack(){
      this.isshowEdit = false; //新建页面隐藏
      this.isshowList = true; //列表页面显示
      this.getList();
    },
    /**
     * 新增页面显示
     */
    handleAdd() {
      this.isshowAdd = true; //新建页面显示
      this.isshowList = false; //列表页面隐藏
      this.isshowEdit= false; //列表页面隐藏
      this.docDate = new Date();
      this.describe = '';
      this.detail = [
        {
          BorrowLine_BorrowMoney: 0, //金额
          YBL_Department: "", //费用承担部门
          BorrowLine_YBL: "", //费用类型
          balance: "", //预算金额
        }
      ];
      this.Type = 0;
      this.getbudgetTypeAndArrangeModel();
      /* this.getMonth(res=>{
        console.log(res,'res');
        let detail = this.detail;//this.detail是 每行的对象
        detail.forEach((item,index)=>{
          item.Month = res[0].Code;
        })
      }); */
    },
    //获得调整方式，预算类型获得调整方式，预算类型
    getbudgetTypeAndArrangeModel(){
      axios
        .get("budgetTypeAndArrangeModel")
        .then(res => {
          this.AdjustModelList = res.AdjustMode; //调整方式
          this.BudgetTypeList = res.BudgetType; //	预算类型
          this.AdjustModel = res.AdjustMode[0].Code;
          this.BudgetType = res.BudgetType[0].Code;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //获取月份
    getMonth(cb){
      axios
        .get("getMonth")
        .then(res => {
          this.Month = res;
          cb && cb(res);
        })
        .catch(err => {
          console.log(err);
        })
    },
    /*
     *	显示编辑界面
     */
    handleEdit(index,row){
      if(!row){
        this.showNum = this.$route.query.showNum;        
        this.DocNo = this.$route.query.key;        
      }else{
        this.DocNo = row.BA_DocNO;
      }
      console.log(row,'row');      
      console.log(this.DocNo,'this.DocNo');
      this.isshowEdit = true; //编辑显示
      this.isshowList = false; //列表隐藏 
      this.isshowAdd = false;
      //获得调整方式，预算类型
      this.getbudgetTypeAndArrangeModel();
      //获取月份
      this.getMonth();
      //获取详细信息
      axios
        .get("getBudgetOperation",{key:this.DocNo})
        .then(res => {
          console.log(res,'详细信息');
          this.Type = res.Type;
          this.budgetDetail = res.entity;
          this.DocNo = this.budgetDetail.BA_DocNO;
          this.docDate = this.budgetDetail.BA_DocDate;
          this.BudgetType = this.budgetDetail.BA_BudgetType;//绑定Code
          this.AdjustModel = this.budgetDetail.BA_AdjustMode;//绑定Code
          this.describe = this.budgetDetail.BA_Abstract;
          axios
          .get('getBudgetAdjustLine',{key:this.DocNo})//这里获取
          .then(res => {
            this.detailTemp = res;//明细列表
            console.log(this.detailTemp,'明细列表');
            this.detail = [];
            let getCostTypePromiseAll = [];
            // 拿到明细列表后循环push' 给 detail 添加多两个字段
            for (let i = 0; i < this.detailTemp.length; i++) {
              this.detail.push({
                ...this.detailTemp[i],
                BorrowLine_BorrowMoney: this.detailTemp[i].BAL_Adjust,
                Month: this.detailTemp[i].YBL_Month,
                balance: 0,
                costTypes: []
              });
              getCostTypePromiseAll.push(
                this.getCostType(
                  this.detail[i].YBL_Department, // 部门id
                  this.detail[i].BorrowLine_YBL, //  明细id
                  i
                )
              );
            }
          
            //  获取 费用类型
            Promise.all(getCostTypePromiseAll).then(resultArr => {
              // 循环
              for (let i = 0; i < this.detail.length; i++) {
                // 每条明细赋值费用类型数据
                this.detail[i].costTypes = resultArr[i];
                this.$set(this.detail[i], "balance", this.detail[i].YBL_ThisLeaved)
                this.$set(this.detail[i], "BorrowLine_YBL", this.detail[i].BAL_YBL)
                console.log(this.detail, "detail")
              }
            });
            //判断状态获取沟通
            if(this.communiTypes==1||this.communiTypes==2){ 
              this.dialogCommunicationVisible = true;
              this.isshowLauch = false;
              let all = [
                axios.get('CommunicationContent',{
                  key:this.DocNo,
                  DocType:this.DocType
                }),
                axios.get('LaunchList',{
                  key:this.DocNo,
                  DocType:this.DocType
                }),
              ];
              this.axios.all(all).then(
                this.axios.spread((res1,res2)=>{
                  this.CommunicationContentList = res1;//获得沟通内容
                    for(var i=0;i<this.CommunicationContentList.length;i++){
                      if(this.CommunicationContentList[i].Img==''){//如果是空的
                        const ac = this.acquiescenceImg;
                        this.CommunicationContentList[i].Img = ac;//赋值默认头像
                      }
                    }
                    this.requestEmp = res2.RequestEmp;//申请人ID
                    this.LaunchList = res2.us;//获得沟通对象  
                })
              )   
            }
          })
        })
        .catch(err => {
          console.log(err);
        });
      
      
    },
    addSave() {
      let myArr = [];
      let detail = this.detail;
      detail.forEach(value => {
        let money = value.BorrowLine_BorrowMoney; //金额
        let ybl = value.BorrowLine_YBL; //费用类型
        let temp = `{"Money":${money},"BLID":"${ybl}"}`;
        myArr.push(temp);
      });
      this.Budget = myArr.join(","); //逗号分割并拼接备份给json字符串传参
      this.Budget = `[` + this.Budget + `]`;
      let params = {
        BA_DocDate: this.docDate,
        BA_BudgetType: this.BudgetType,
        BA_AdjustMode: this.AdjustModel,
        BA_Abstract: this.describe,
        BA_DocStatus: 1, //1=保存 2=提交
        key: null,
        Budget: this.Budget
      };
      axios
        .post("BudgetAdjustSubmit", params)
        .then(res => {
          if (res.Success == true) {
            this.$message({
              message: res.Message,
              type: "success",
              duration:1200
            });
            this.isshowAdd = false;
            this.isshowEdit = false;
            this.isshowList = true;
            this.getList();
          } else {
            this.$message({
              message: res.Message,
              type: "warning",
              duration:1500  
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    addSubmit() {
      let myArr = [];
      let detail = this.detail;
      detail.forEach(value => {
        let money = value.BorrowLine_BorrowMoney; //金额
        let ybl = value.BorrowLine_YBL; //费用类型
        let temp = `{"Money":${money},"BLID":"${ybl}"}`;
        myArr.push(temp);
      });
      this.Budget = myArr.join(","); //逗号分割并拼接备份给json字符串传参
      this.Budget = `[` + this.Budget + `]`;
      let params = {
        BA_DocDate: this.docDate,
        BA_BudgetType: this.BudgetType,
        BA_AdjustMode: this.AdjustModel,
        BA_Abstract: this.describe,
        BA_DocStatus: 2, //1=保存 2=提交
        key: null,
        Budget: this.Budget
      };
      axios
        .post("BudgetAdjustSubmit", params)
        .then(res => {
          if (res.Success == true) {
            this.$message({
              message: res.Message,
              type: "success",
              duration:1200
            });
            this.isshowAdd = false;
            this.isshowEdit = false;
            this.isshowList = true;
            this.getList();
          } else {
            this.$message({
              message: res.Message,
              type: "warning",
              duration:1500  
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    editSave(){
      let myArr = [];
      let detail = this.detail;
      detail.forEach(value => {
        let money = value.BorrowLine_BorrowMoney; //金额
        let ybl = value.BorrowLine_YBL; //费用类型
        let temp = `{"Money":${money},"BLID":"${ybl}"}`;
        myArr.push(temp);
      });
      this.Budget = myArr.join(","); //逗号分割并拼接备份给json字符串传参
      this.Budget = `[` + this.Budget + `]`;
      let params = {
        BA_DocDate: this.docDate,
        BA_BudgetType: this.BudgetType,
        BA_AdjustMode: this.AdjustModel,
        BA_Abstract: this.describe,
        BA_DocStatus: 1, //1=保存 2=提交
        key: null,
        Budget: this.Budget
      };
      axios
        .post("BudgetAdjustSubmit", params)
        .then(res => {
          if (res.Success == true) {
            this.$message({
              message: res.Message,
              type: "success",
              duration:1200
            });
            this.isshowAdd = false;
            this.isshowEdit = false;
            this.isshowList = true;
            this.getList();
          } else {
            this.$message({
              message: res.Message,
              type: "warning",
              duration:1500  
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    editSubmitForm(){
      let myArr = [];
      let detail = this.detail;
      detail.forEach(value => {
        let money = value.BorrowLine_BorrowMoney; //金额
        let ybl = value.BorrowLine_YBL; //费用类型
        let temp = `{"Money":${money},"BLID":"${ybl}"}`;
        myArr.push(temp);
      });
      this.Budget = myArr.join(","); //逗号分割并拼接备份给json字符串传参
      this.Budget = `[` + this.Budget + `]`;
      let params = {
        BA_DocDate: this.docDate,
        BA_BudgetType: this.BudgetType,
        BA_AdjustMode: this.AdjustModel,
        BA_Abstract: this.describe,
        BA_DocStatus: 2, //1=保存 2=提交
        key: null,
        Budget: this.Budget
      };
      axios
        .post("BudgetAdjustSubmit", params)
        .then(res => {
          if (res.Success == true) {
            this.$message({
              message: res.Message,
              type: "success",
              duration:1200
            });
            this.isshowAdd = false;
            this.isshowEdit = false;
            this.isshowList = true;
            this.getList();
          } else {
            this.$message({
              message: res.Message,
              type: "warning",
              duration:1500  
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    editSubmit(){
      this.getState();
      if(this.communiTypes===2){ 
        this.isshowLauch = true;
        this.dialogCommunicationVisible = true;
      } else {
        this.editSubmitForm();
      }
    },
    /**
     * 预算明细添加行
     */
    addlist() {
      this.detail.push({
        BorrowLine_BorrowMoney: 0,
        Month: this.Month[0].Code,
        YBL_Department: "",
        BorrowLine_YBL: "",
        balance: ""
      });
    },  
    //沟通窗口打开 
    Communication(){
      this.dialogCommunicationVisible = true;
      this.isshowLauch=false;
      let all = [
          axios.get('CommunicationContent',{
            key:this.DocNo,
            DocType:this.DocType
          }),
          axios.get('LaunchList',{
            key:this.DocNo,
            DocType:this.DocType
          }),
          axios.get('getCommuniState',{
            key:this.DocNo,
            DocType:this.DocType,
            types:this.Type
          })
      ];
      this.axios.all(all).then(
        this.axios.spread((res1,res2,res3)=>{
            this.CommunicationContentList = res1;//获得沟通内容
            for(var i=0;i<this.CommunicationContentList.length;i++){
              if(this.CommunicationContentList[i].Img==''){//如果是空的
                const ac = this.acquiescenceImg;
                this.CommunicationContentList[i].Img = ac;//赋值默认头像
              }
            }
            this.requestEmp = res2.RequestEmp;//申请人ID
            this.LaunchList = res2.us;//获得沟通对象  
            this.communiTypes = res3;//获取沟通状态
        })
      )   
    },
    //允许提交者编辑单据Change事件
    launchChange(e){
      console.log(e,'e');
      if(e){
        console.log(this.requestEmp,'this.requestEmp');
        console.log(this.launch,'this.launch');
        let bo=true;
        for(let i=0;i<this.launch.length;i++)
        { 
          if(this.launch[i]==this.requestEmp)
          bo=false;      
        }
        if(bo)this.launch.push(this.requestEmp);
      }
    },
    //确认后提交
    CommunicationDetermine(){
      if(this.isshowLauch == true)
      {
        this.$confirm('回复沟通单据将会自动提交，不可再编辑!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.Communicate();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });           
        });
      }else{
        this.Communicate();
      }
    },
    //沟通窗口 确定按钮
    Communicate(){
      let user='';
      for(let i=0;i<this.launch.length;i++){ 
          user+=i!=0?',':'';
          user+=this.launch[i];
      }    
      axios.get('AddCommunicate',{
          key:this.DocNo,
          DocType:this.DocType,
          msg:this.contentInput,
          user:user,
          bj:this.launchChecked ? 1 : 0,
          type:this.communiTypes
      }).then(res=>{
          if(res.Success===true){
            if(this.isshowLauch == true)
            this.editSubmitForm();
            //获得沟通内容
            this.getContent();
            this.$message({
              message: res.Message,
              type: 'success',
              duration: 1200
            })
            this.getState();
            this.contentInput = '';
            
          }else{
            this.$message({
              message: res.Message,
              type: 'warning',
              duration: 1200
            })
          }
      }).catch(err=>{
          console.log(err);
      })      
    },
    //获取内容
    getContent(){
      axios.get('CommunicationContent',{
        key:this.DocNo,
        DocType:this.DocType
      }).then(res=>{
        this.CommunicationContentList = res;
        for(var i=0;i<this.CommunicationContentList.length;i++){
            if(this.CommunicationContentList[i].Img==''){//如果是空的
                const ac = this.acquiescenceImg;
                this.CommunicationContentList[i].Img = ac;//赋值默认头像
            }
        }    
      })
    },
    //获取type
    getState(){
      axios.get('getCommuniState',{
        key:this.DocNo,
        DocType:this.DocType,
        types:this.Type
      }).then(res=>{
        this.communiTypes = res;
        console.log(this.communiTypes,'type1');        
      }).catch(err=>{
        console.log(err);
      })
    },
    //审核提示
    checkMsg() {
      axios
        .get("checkMsg")
        .then(res => {
          this.Msg = res;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //审核
    auditBudget(){
      axios
        .get('ExamineCommunication',{
          key:  this.DocNo,
          DocType:  this.DocType
        }).then(res => {
          if(res.Data === '1'){
            this.$confirm(res.Message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.ToExamineBudget();
            }).catch(() => {
                this.$message({
                type: "info",
                message: "已取消"
              });
            });
          } else if(res.Data === '2') {
            this.$message({
              type: "warning",
              message: res.Message,
              duration: 1500
            });
          }else
            this.ToExamineBudget();
        })
        .catch(err => {
          console.log(err);
        })
    },
    ToExamineBudget(){
      /* this.DocNo */
      this.checkMsg(); //审核提示
      this.$confirm(this.Msg, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          axios
            .get("budgetToExamine", {
              key: this.DocNo,
              type: 0 //0审核 1驳回
            })
            .then(res => {
              this.$message({
                type: "success",
                message: res
              });
              setTimeout(() => {
                this.$router.push({
                  path: "/notAudit"
                });
              }, 500);
            })
            .catch(err => {
              console.log(err);
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
    },
    //驳回预算调整单提示
    rejectBudget(){
      axios
        .get('ExamineCommunication',{
          key:  this.DocNo,
          DocType:  this.DocType
        }).then(res => {
          if(res.Data === '1'){
            this.$confirm(res.Message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.IsRejectBudget();
            }).catch(() => {
                this.$message({
                type: "info",
                message: "已取消"
              });
            });
          }else
            this.IsRejectBudget();
        })
        .catch(err => {
          console.log(err);
        })
    },
    //驳回
    IsRejectBudget(){
      this.DocNo = getQueryParam("key");
      this.$prompt("请您输入驳回的理由", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
        .then(({
          value
        }) => {
          this.$message({
            type: "success",
            message: "你的驳回的理由是：" + value
          });
          axios
            .get("budgetToExamine", {
              key: this.DocNo,
              type: 1, //0审核 1驳回
              Reason: value
            })
            .then(res => {
              this.$message({
                message: res,
                type: "success"
              });
              setTimeout(() => {
                this.$router.push({
                  path: "notAudit"
                });
              }, 500);
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    /**
     * @param index [当前行数]
     * @param id [选中的部门code]
     */
    changeSelect(index, id) {
      // 获取费用类型方法获取费用类型方法
      this.getCostType(id, null, index).then(res => {
        this.detail[index].costTypes = res;
        /* if(this.Type!==2 && this.Type!==3){//0添加  1修改 2查看  3有审核权限
          this.detail[index].BorrowLine_YBL =res[0] ? res[0].ID : '';   // 这个设置还是没有显示费用类新 balance 先把费用清除掉了先
        } */
      });
    },

    //月份改变的时候
    changeMonth(index,month){
      this.MonthParams = month;
    },
    /**
     * @param code [部门id]
     * @param YBLID 明细ID 
     * 
     */   
    getCostType(code, YBLID, index) {
      console.log(this.BudgetType,'BudgetType');
      //费用类型
      var params = {
        id: code,
        BudgetType:this.Type===2||this.Type===3?101: this.BudgetType, //3是借款 1是报销
        Month: this.detail[index].Month, //this.MonthParams, //默认为空就是当前月份
        /* type: this.Type, */
        YBLID: YBLID
        //1是新增或修改 2审核查看
      };
      return axios.post("getBudgetItem", params);
    },

    ChangeMoney(index) {
      console.log(1)
      //费用类型绑定 与 预算金额
      const BorrowLine_YBL = this.detail[index].BorrowLine_YBL; //费用类型ID
      this.detail[index].costTypes.map(
        item =>
          BorrowLine_YBL == item.ID
            ? (this.detail[index].balance = item.YBL_ThisLeaved)
            : ""
      );
    },
    // 撤销
    repeal(index, row) {
      this.$confirm("确认撤销吗?", "提示", {
        type: "warning"
      }).then(() => {
        axios
          .get("revokebudgetAdjust", {
            key: row.BA_DocNO
          })
          .then(res => {
            this.$message({
              message: res.Message,
              type: "success"
            });
            this.getList();
          });
      });
    },
    //删除
    handleDel(index, row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning"
      }).then(() => {
        axios
          .get("deleBudgetAdjust", {
            key: row.BA_DocNO
          })
          .then(res => {
            this.$message({
              message: res.Message,
              type: "success"
            });
            this.getList();
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 获取费用承担部门数据
    bear() {
      axios.get("getDept").then(res => {
        this.bears = res;
        /* for(let i=0;i<this.detail.length;i++) {
          console.log(this.detail[i].YBL_Department,'this.detail[i].YBL_Department')
          this.detail[i].YBL_Department = res[0].CODE;
        } */

      });
    },
    // 明细部分删除按钮
    handleDelete(index) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.detail.splice(index, 1);
        this.$message({
          message: "已删除",
          type: "success"
        });
      });
    },
    Clear() {
      this.detail = [];
    },
    //外部流程图
    checkflowRow(index, rows) {
      this.checkflowRowVisible = true;
      let DocNo = rows.BA_DocNO;
      if (this.checkflowRowVisible == true) {
        if (rows.DocStatus == "新建") {
          //如果是新建状态就直接给个提示
          this.checkflowRowVisible = false;
          this.$message({
            message: "新建状态未有流程图",
            type: "warning"
          });
        } else if (rows.DocStatus == "无效") {
          //如果是无效状态也直接给个提示
          this.checkflowRowVisible = false;
          this.$message({
            message: "未找到相对应的流程图",
            type: "warning"
          });
        } else {
          //否则直接请求拿列表数据
          this.docViewloading = true;
          axios
            .get("checkFlow", {
              DocNo: DocNo, //单据编号
              DocType: 203 //类型为预算调整单
            })
            .then(res => {
              this.docRowView = res;
              setTimeout(() => {
                this.docViewloading = false;
              }, 1200);
            })
            .catch(err => {
              console.log(err);
            });
        }
      }
    },
    //内部流程图
    checkflow(){
      this.checkflowVisible = true;
      this.docViewloading = true;
      axios
        .get("checkFlow", {
          DocNo: this.DocNo, //单据编号
          DocType: 203 //类型为预算调整单
        })
        .then(res => {
          this.docView = res;
          setTimeout(() => {
            this.docViewloading = false;
          }, 1200);
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 审核 / 申请 页面
    /* AuditAndApply() {
      this.showNum = this.$route.query.showNum;
      this.DocNo = this.$route.query.key;
      let showNum = this.showNum;
      console.log(typeof showNum,'showNum');
      console.log(showNum,'showNum');
      if (showNum === 3) {
        //2的时候是编辑页
        this.isshowEdit = true;
        this.isshowList = false;
        this.isshowAdd = false;
        //获得调整方式，预算类型
      this.getbudgetTypeAndArrangeModel();
      //获取月份
      this.getMonth();
      //获得调整方式，预算类型
      axios
        .get("budgetTypeAndArrangeModel")
        .then(res => {
          console.log(res, '获得调整方式，预算类型');
          this.AdjustModelList = res.AdjustMode; //调整方式
          this.BudgetTypeList = res.BudgetType; //	预算类型
        })
        .catch(err => {
          console.log(err);
        });
      //获取详细信息
      axios
        .get("getBudgetOperation",{key:this.DocNo})
        .then(res => {
          console.log(res,'详细信息');
          this.Type = res.Type;
          this.budgetDetail = res.entity;
          this.DocNo = this.budgetDetail.BA_DocNO;
          this.docDate = this.budgetDetail.BA_DocDate;
          this.BudgetType = this.budgetDetail.BA_BudgetType;//绑定Code
          this.AdjustModel = this.budgetDetail.BA_AdjustMode;//绑定Code
          this.describe = this.budgetDetail.BA_Abstract;
        })
        .catch(err => {
          console.log(err);
        });
      axios
        .get('getBudgetAdjustLine',{key:this.DocNo})
        .then(res => {
          this.detailTemp = res;//明细列表
          console.log(this.detailTemp,'明细列表');
          this.detail = [];
          let getCostTypePromiseAll = [];
          // 拿到明细列表后循环push' 给 detail 添加多两个字段
          for (let i = 0; i < this.detailTemp.length; i++) {
            this.detail.push({
              ...this.detailTemp[i],
              BorrowLine_BorrowMoney: this.detailTemp[i].BAL_Adjust,
              Month: this.detailTemp[i].YBL_Month,
              balance: 0,
              costTypes: []
            });

            getCostTypePromiseAll.push(
              this.getCostType(
                this.detail[i].YBL_Department, // 部门id
                this.detail[i].BorrowLine_YBL, //  明细id
                i
              )
            );
          }
        
          //  获取 费用类型
          Promise.all(getCostTypePromiseAll).then(resultArr => {
            // 循环
            for (let i = 0; i < this.detail.length; i++) {
              // 每条明细赋值费用类型数据
              this.detail[i].costTypes = resultArr[i];
              this.$set(this.detail[i], "balance", this.detail[i].YBL_ThisLeaved)
              this.$set(this.detail[i], "BorrowLine_YBL", this.detail[i].BAL_YBL)
              //  this.detail[i].BorrowLine_YBL =  Number(this.detail[i].BAL_YBL.toString())
              console.log(this.detail, "detail")
            }
          });
          //判断状态获取沟通
          if(this.communiTypes==1||this.communiTypes==2){ 
            this.dialogCommunicationVisible = true;
            this.isshowLauch = false;
            let all = [
              axios.get('CommunicationContent',{
                key:this.DocNo,
                DocType:this.DocType
              }),
              axios.get('LaunchList',{
                key:this.DocNo,
                DocType:this.DocType
              }),
            ];
            this.axios.all(all).then(
              this.axios.spread((res1,res2)=>{
                this.CommunicationContentList = res1;//获得沟通内容
                  for(var i=0;i<this.CommunicationContentList.length;i++){
                    if(this.CommunicationContentList[i].Img==''){//如果是空的
                      const ac = this.acquiescenceImg;
                      this.CommunicationContentList[i].Img = ac;//赋值默认头像
                    }
                  }
                  this.requestEmp = res2.RequestEmp;//申请人ID
                  this.LaunchList = res2.us;//获得沟通对象  
              })
            )   
          }
        })
      }
    } */
  },
  mounted() {
    this.getList();
    /* this.AuditAndApply(); */
    this.bear();
    this.checkMsg(); //审核提示
    /* console.log(this.$route.query.showNum,'this.$route.query.showNum'); */
    if(this.$route.query.showNum && this.$route.query.key){
      this.handleEdit();
    }
  }
};
</script>

<style scoped lang="scss">
@import "../../common/css/index.css";
.toolbar h2 {
  margin: 10px auto 0 0;
}
.HideTable th {
  width: 16.6666%;
}
</style>
